import {getDicts} from "@/api/system/dict/data";

export default {
  data() {
    return {
      dictTypes: [], //需要的字典key，会被组件数据覆盖
      _filterFunc: {},       // 过滤器函数
      _dictData: {}, //字典map
      _myDictFilterTracker: 0 //用来追踪map数据的改变
    }
  },
  computed: {
    _dictDataComputed() { //用来追踪map数据的改变
      const x = this.$data._myDictFilterTracker;
      return this.$data._filterFunc;
    },
    dictStore() {
      const x = this.$data._myDictFilterTracker;
      return this.$data._dictData;
    }
  },
  methods: {
    _getSysDictData(dictKey) {
      getDicts(dictKey).then(res => {
        this.$data._dictData[dictKey] = res.data || [];
        this.$data._filterFunc[dictKey] = val => {		// 过滤器注册到_filterFunc中
          const list = this.$data._dictData[dictKey];
          return this.selectDictLabel(list, val);
        };
        this.$data._myDictFilterTracker += 1;
      })
    },

    _dictFilter(val, dictKey) {
      const func = this._dictDataComputed;
      const mth = func && func[dictKey];
      return mth && mth(val) || val
    },
  },
  mounted() {
    if (this.dictTypes) {
      this.dictTypes.forEach(key => {
        this._getSysDictData(key);
      })
    }
  }
}
